package cn.cqie.frame.service.impl;

import cn.cqie.frame.bo.query.QueryCourseBo;
import cn.cqie.frame.entity.Course;
import cn.cqie.frame.mapper.CourseMapper;
import cn.cqie.frame.service.CourseService;
import cn.cqie.frame.utils.AssertUtil;
import cn.cqie.frame.utils.MyPageHelper;
import cn.cqie.frame.vo.CourseVo;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHL
 * @since 2021-10-09
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private CourseService courseService;

    /**
     * 新增or更新课程信息
     * @param bo
     * @return
     */
    @Override
    public CourseVo saveOrUpdateCourse(Course bo) {
        LocalDateTime sysTime = LocalDateTime.now();
        bo.setCreateTime(sysTime);
        bo.setUpdateTime(sysTime);
        boolean insert = courseService.saveOrUpdate(bo);
        AssertUtil.isTrue(insert, "插入/更新菜单失败");
        return BeanUtil.toBean(bo, CourseVo.class);
    }


    /**
     * 分页查询课程信息
     * @param bo
     * @return
     */
    @Override
    public List<CourseVo> list(QueryCourseBo bo) {
        MyPageHelper.startPage(bo);
        LambdaQueryWrapper<Course> lqw = new LambdaQueryWrapper<>();
        lqw.like(bo.getKeywords()!=null,Course::getName,bo.getKeywords());
        List<Course> courseList = baseMapper.selectList(lqw);
        return entity2Vo(courseList);

    }

    /**
     * 删除课程信息
     * @param courseId
     * @return
     */
    @Override
    public Boolean deleterCourse(Integer courseId) {
        boolean b = courseService.removeById(courseId);
        return b;
    }

    /**
     * 格式转换
     * @param collection
     * @return
     */
    private List<CourseVo> entity2Vo(List<Course> collection) {
        List<CourseVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Course> page = (Page<Course>) collection;
            Page<CourseVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }
}
